package com.ywger.web.aspect;

import com.ywger.integration.exception.IntegrationException;
import com.ywger.service.constants.ResultCode;
import com.ywger.service.exception.BizException;
import com.ywger.service.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * @author chenmeng
 * @date 2018-12-11 15:43
 * @desc  统一异常处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 业务异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public Result<String> handlerBizException(BizException e) {
        log.error("[BizException]:",e);
        return Result.ofError(e.getResultCode(),e.getResultMessage());
    }


    /**
     * 业务异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = IntegrationException.class)
    public Result<String> handlerIntegrationException(IntegrationException e) {
        log.error("[IntegrationException]:",e);
        return Result.ofError(e.getResultCode(),e.getResultMessage());
    }
    /**
     * 参数绑定异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> handle(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        List<ObjectError> errors =result.getAllErrors();
        StringBuffer errorMsg=new StringBuffer();
        errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
        log.error("[参数校验异常]：",e);
        return Result.ofError(ResultCode.PARAM_ERROR.name(),errorMsg.toString()) ;
    }

    /**
     * 参数类型转换错误
     *
     * @param e 错误
     * @return 错误信息
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public Result<String> parameterTypeException(HttpMessageConversionException e){
        log.error("[类型转换错误]",e);
        return Result.ofError(ResultCode.PARAM_ERROR.name(),e.getMessage()) ;

    }

    /**
     * 系统异常，未知异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result<String> handlerException(Exception e) {
        log.error("[服务器异常]：",e);
        return Result.ofError(ResultCode.SERVER_ERROR.name(),e.getMessage());
    }



}
